package br.embedded.socialapp.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.embedded.socialapp.business.UserManager;
import br.embedded.socialapp.exceptions.UserException;

/**
 * Servlet implementation class AccountServlet
 */
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AccountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		registerNewUser(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		registerNewUser(request, response);
	}
	
	private void registerNewUser(HttpServletRequest request, HttpServletResponse response)
	{
		String userLogin = request.getParameter("user_login");
		String firstName = request.getParameter("first_name");
		String lastName = request.getParameter("last_name");
		String passwd = request.getParameter("passwd");
		
		String[] parameters = {userLogin, firstName, lastName, passwd};
		
		if (validateParameters(parameters))
		{
			try {
				UserManager.getInstance().createUser(userLogin, firstName, lastName, passwd);
				response.sendRedirect("/SocialNetsApp/login.jsp");
			} catch (UserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private boolean validateParameters(String[] params)
	{
		for (String param : params) {
			if (param == null || param.isEmpty())
				return false;
		}
		return true;
	}
}
